using System;
using System.Web;

namespace ASPNETVN.PORTAL.Components.Helpers
{
    public class UrlRewriter : IHttpModule
    {
        #region IHttpModule Members

        public void Init(HttpApplication context)
        {
            context.BeginRequest += Context_BeginRequest;
        }

        public void Dispose()
        {
        }

        #endregion

        private static void Context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            string url = app.Request.RawUrl.ToLower();

            string returnUrl = "";
            if (app.Request.QueryString["ReturnUrl"] != null)
                returnUrl = "&ReturnUrl=" + app.Request.QueryString["ReturnUrl"];

            if (url.Contains("/signin.aspx"))
            {
                app.Context.RewritePath("Default.aspx", "", "cid=SignIn" + returnUrl);
            }
            else if (url.Contains("/register.aspx"))
            {
                app.Context.RewritePath("Default.aspx", "", "cid=Register" + returnUrl);
            }
            else if (url.Contains("/registercompleted.aspx"))
            {
                app.Context.RewritePath("Default.aspx", "", "cid=RegisterCompleted" + returnUrl);
            }
            else if (url.Contains("/activeuser.aspx"))
            {
                app.Context.RewritePath("Default.aspx", "", "cid=ActiveUser&ActiveCode=" + app.Request.QueryString["ActiveCode"] + returnUrl);
            }
            // Profile.
            else if (url.Contains("/profile.aspx"))
            {
                string option = string.Empty;
                if (app.Request.QueryString["option"] != null)
                {
                    option = "&option=" + app.Request.QueryString["option"];
                }
                app.Context.RewritePath("Default.aspx", "", "cid=Profile" + option + returnUrl);
            }
            // Password Recovery.
            else if (url.Contains("/passwordrecovery.aspx"))
            {
                app.Context.RewritePath("Default.aspx", "", "cid=PasswordRecovery" + returnUrl);
            }
            else if (url.Contains("/search.aspx"))
            {
                app.Context.RewritePath("Default.aspx", "", "cid=Search&value=" + app.Request.QueryString["value"]);
            }
            else if (url.Contains("/googlesearch.aspx"))
            {
                app.Context.RewritePath("Default.aspx", "", "cid=GoogleSearch");
            }

        }
    }
}